<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BAEventCooker
 *
 * @author jianfeng
 */
class BAEventCooker extends BCooker {

    public function init($data = NULL) {
        parent::init($data);

        //special for wePage type, add template for wePage type
        //if (!$sender instanceof BUIScreen && !$sender instanceof BUIOperation) {
        $eventViewPath = $this->getViewPathOfEvent();
        if ($eventViewPath !== FALSE) {
            Blyn::app()->getUIManager()->getUpdateControl()->setViewPath($eventViewPath);
        }
        //}
    }

    public function addEventType($name, $alias = NULL, $parent = NULL) {
        $category = new BACategory();
        $rootNode = $category->getRootNode();
        if ($parent != NULL && !$parent instanceof BACategory) {
            if (is_string($parent) && strpos($parent, 'eventType') === FALSE)
                $parent = 'eventType.' . $parent;
            $parent = $rootNode->getChild($parent);
        }

        if (!$parent instanceof BACategory) {
            $parent = $rootNode->getChild('eventType');
            if (!$parent instanceof BACategory) {
                $parent = $rootNode->addChild('eventType');
            }
        }

        //add event type here
        $type = $parent->addChild($name);

        //add alias for event type
        if ($alias == NULL)
            $alias = $type->getName();

        $aliasTable = new BASpaceSheet('eventTypeAlias');

        $list = $aliasTable->getList(array('itemData' => array('typeFullName' => $type->getFullName())));

        if (!$list)
            $aliasTable->addList(array('typeFullName' => $type->getFullName(), 'typeAlias' => $alias));

        return $type;
    }

    /**
     * 
     * @param BACategory $eventType, OR FULLNAME OF EVENTTYPE
     * @return boolean
     */
    public function getEventTypeAlias($eventType) {
        $typeFullName = NULL;
        if (is_string($eventType))
            $typeFullName = $eventType;
        if (is_numeric($eventType) && $eventType > 0) {
            $eventType = new BACategory($eventType);
        }
        if ($eventType instanceof BACategory)
            $typeFullName = $eventType->getFullName();

        if ($typeFullName != NULL) {
            $aliasTable = new BASpaceSheet('eventTypeAlias');
            $list = $aliasTable->getList(array('itemData' => array('typeFullName' => $typeFullName)));
            if ($list) {
                return $list->getItem('typeAlias')->getValue();
            }
        }

        return FALSE;
    }

    /**
     * this function use to get eventType list, can specify parent as 
     * 'eventType.admin' or only 'admin'
     * @param string resultFormat: can be 'object','name','fullname' and 'alias'
     */
    public function getEventTypeList($resultFormat = 'object', $parent = NULL, $data = NULL) {
        $category = new BACategory();
        $rootNode = $category->getRootNode();
        if ($parent != NULL && !$parent instanceof BACategory) {
            if (is_string($parent) && strpos($parent, 'eventType') === FALSE)
                $parent = 'eventType.' . $parent;
            $parent = $rootNode->getChild($parent);
        }

        if (!$parent instanceof BACategory) {
            $parent = $rootNode->getChild('eventType');
            if (!$parent instanceof BACategory) {
                $parent = $rootNode->addChild('eventType');
            }
        }

        $typeList = $parent->getChildrenAsLeaf(NULL, TRUE);

        //this will remove unchangeless type from type list
        $changelessType = $rootNode->getChild('eventType.changeless');
        foreach ($typeList as $key => $type) {
            if ($type->isChildOf($changelessType)) {
                unset($typeList[$key]);
            }
        }

        if (strtolower($resultFormat) == 'fullname') {
            $list = array();
            foreach ($typeList as $id => $type) {
                $fullName = $type->getFullName();
                $list[$id] = $fullName;
            }
            return $list;
        }

        if (strtolower($resultFormat) == 'name') {
            $list = array();
            foreach ($typeList as $id => $type) {
                $name = $type->getName();
                $list[$id] = $name;
            }
            return $list;
        }
        if (strtolower($resultFormat) == 'alias') {
            $list = array();
            foreach ($typeList as $id => $type) {
                $fullName = $type->getFullName();
                $alias = $this->getEventTypeAlias($fullName);
                $list[$id] = $alias;
            }
            return $list;
        }
        return $typeList;
    }

    public function getEventTypeByEvent($event) {
        if ($event != NULL) {
            $eventType = BACategory::getMemberCategory($event);
            return $eventType;
        }
    }

    public function getEventTypeByName($typeName) {

        if (strpos($typeName, 'eventType') === FALSE) {
            $typeName = 'eventType.' . $typeName;
        }

        $categroyRoot = BACategory::getRoot();
        //get by fullname first
        $child = $categroyRoot->getChild($typeName);
        if ($child != NULL)
            return $child;

        //then try to get from root of event category root
        $category = new BACategory();
        $eventCategroyRoot = $category->getRootNode();
        return $eventCategroyRoot->getChild($typeName);
    }

    public function getCurrentEventType($data = NULL) {
        $event = $this->getCurrentEvent();
        return $this->getEventTypeByEvent($event);
    }

    /**
     * this function will check if eventType is used in currentApp, 
     * if used, remove from list
     * @param type $eventTypeListData
     */
    public function populateAvailableEventTypeListData($eventTypeListData) {
        $listData = $eventTypeListData;
        foreach ($listData as $name => $value) {
            $type = $this->getEventTypeByName($name);
            if ($type == NULL) {
                $this->addEventType($name, $value);
            } else {
                $eventTypeCountTable = new BAEventSheet(NULL, 'eventTypeCount');
                $typeId = $type->getId();
                $list = $eventTypeCountTable->getList(array('itemData' => array('eventTypeId' => $typeId)));
                if ($list != NULL) {//means eventType has been used，THEN NOT LIST FOR ADDING
                    unset($listData[$name]);
                }
            }
        }
        return $listData;
    }

    public function addEvents($eventList = array()) {

        $eventTable = new BAEventSheet();
        $count = $eventTable->getCount();

        if ($count != NULL && $count > 0) {
            return;
        } else {
            foreach ($eventList as $eventData) {
                $eventName = NULL;
                $eventType = 'NULL';
                if (is_string($eventData)) {
                    $eventName = $eventData;
                    $eventData = NULL;
                }
                if (is_array($eventData) && isset($eventData['eventType'])) {
                    $eventType = $eventData['eventType'];
                    unset($eventData['eventType']);
                }
                $this->addEvent($eventName, $eventType, $eventData);
            }
        }
    }

    /**
     * this function use to add event manually, to add event by this function,
     * will follow some rules:
     * 1)operation_eventName file if exist, use it as home of event
     * 2)will find event first, if save of eventName+eventType exist, not add it
     * @param type $eventType
     * @param type $eventName
     * @param type $eventData
     * @return type
     */
    public function addEvent($eventName, $eventType = NULL, $eventData = array()) {

        //if not specify type, set eventName as type and add type into eventType
        if ($eventType == NULL) {
            $eventType = $this->addEventType($eventName);
            $eventTypeFullName = $eventType->getFullName();
        }

        if (is_string($eventType) && $eventType != NULL) {
            $eventType = $this->addEventType($eventType);
            $eventTypeFullName = $eventType->getFullName();
        }

        if ($eventType instanceof BACategory)
            $eventTypeFullName = $eventType->getFullName();

        $eventTable = new BAEventSheet();
        //$typeList = $this->getEventTypeList('fullName');
        //if type exist
        //if (in_array($eventTypeFullName, $typeList)) {
        //$eventType = $this->getEventTypeByName($eventType);
        $operations = Blyn::app()->getActiveApp()->getOperations();
        $itemData = array(
            'name' => $eventName,
            'eventTypeId' => $eventType->getId()
        );
        $list = $eventTable->getList(array('itemData' => $itemData));
        if ($eventData != NULL) {
            $itemData+= $eventData;
        }
        //can only add event that not exist
        if (!$list) {
            $list = $eventTable->addList($itemData);
            //add event into type
            $eventType->addMember($list);

            $eventCountTable = new BAEventSheet(NULL, 'eventTypeCount');
            $list2 = $eventCountTable->getList(array('itemData' => array('eventTypeId' => $eventType->getId())));
            if ($list2 != NULL) {
                $count = $list2->getItem('count')->getValue();
                $count +=1;
                $list2->addItem('count', $count);
            } else {
                $eventCountTable->addList(array('eventTypeId' => $eventType->getId(), 'count' => 1));
            }
        }
        //}
        return $list;
    }

    /**
     * format of preload data
     * array(
      'type' => array('weBill' => '买单功能'),
      'event' => array(
      'name' => 'discount10',
      'alias' => '9折买单',
      'discount' => 0.1,
      'roles' => array(
      array(
      'name' => BRole::Role_Space_Admin,
      'eventHome' => 'bill_admin'
      ),
      array(
      'name' => BRole::Role_Space_Member,
      'eventHome' => 'bill_manage'
      )
      )
      ),
      )
     * @param type $eventData
     * @return type
     */
    public function preloadEvent($eventData) {
        $jsonEventData = json_encode($eventData);
        $md5EventData = md5($jsonEventData);

        $cachedEventData = Blyn::app()->getActiveApp()->getCache($md5EventData);
        if ($cachedEventData != NULL && $cachedEventData == $jsonEventData) {
            //return; //means preload already
        } else {
            Blyn::app()->getActiveApp()->setCache($md5EventData, $jsonEventData);
        }
        $roleCooker = new BARoleCooker();
        if (is_array($eventData) && $eventData != NULL) {
            if (isset($eventData['type'])) {
                $typeData = $eventData['type'];
                $oType = $this->getEventType($typeData);
                if ($oType == NULL) {
                    $oType = $this->addEventType($typeData);
                }

                if (isset($eventData['event'])) {
                    $eventData = $eventData['event'];
                    $eventRoles = array(array('name' => BRole::Role_Space_Admin));
                    if (isset($eventData['roles'])) {
                        $eventRoles = $eventData['roles'];
                        unset($eventData['roles']);
                    }

                    $event = $this->addEvent($eventData['name'], $oType, $eventData);
                    $eventId = $event->getId();

                    foreach ($eventRoles as $roleData) {
                        $role = $roleCooker->getRole($roleData);
                        if (isset($roleData['name'])) {
                            unset($roleData['name']);
                        }
                        if ($role != NULL) {
                            $roleId = $role->getId();
                            $list = $roleCooker->getRoleEvent($roleId, $eventId);
                            if ($list == NULL) {
                                $roleCooker->addRoleEvent($roleId, $eventId, $roleData);
                            }
                        }
                    }
                }
            }
        }
    }

    public function populateEventTypeFolderAlias($eventType, $viewName = NULL, $data = NULL) {
        //populate eventTypeName without root part
        $category = new BACategory();
        $categoryRoot = $category->getRootNode();
        $eventTypeRoot = $categoryRoot->getChild('eventType');
        $etRootName = $eventTypeRoot->getFullName();

        if (is_string($eventType)) {
            $eventTypeFullName = $eventType;
        }

        if ($eventType instanceof BACategory) {
            $eventTypeFullName = $eventType->getFullName();
        }

        $eventTypeFolderName = str_replace($etRootName . '.', '', $eventTypeFullName);

        if ($viewName != NULL) {
            $eventViewName = $eventTypeFolderName . '.' . $viewName;
            $viewPath = Blyn::app()->getActiveApp()->getUIManager()->getViewPath($eventViewName);

            if ($viewPath == NULL) {
                $blynViewPath = Blyn::app()->getUIManager()->getViewPath();
                if (file_exists(yii::getPathOfAlias($blynViewPath . '.' . $eventViewName . '.' . $viewName))) {
                    $viewPath = $blynViewPath . '.' . $eventViewName . '.' . $viewName;
                }
            }

            return $viewPath;
        } else {
            $eventTypeFolderAlias = Blyn::app()->getActiveApp()->getUIManager()->getViewPath($eventTypeFolderName);
            if (!is_dir(yii::getPathOfAlias($eventTypeFolderAlias))) {
                $blynViewPath = Blyn::app()->getUIManager()->getViewPath();
                if (is_dir(yii::getPathOfAlias($blynViewPath . '.' . $eventTypeFolderName))) {
                    $eventTypeFolderAlias = $blynViewPath . '.' . $eventTypeFolderName;
                }
            }
            return $eventTypeFolderAlias;
        }
    }

    /**
     * this function will find view path for event,
     * it will first find by event type, if specify template
     * will add template after eventtype view path
     * @param type $event
     * @return string|boolean
     */
    public function getViewPathOfEvent($event = NULL) {

        if ($event == NULL) {

            /*
              $sender = Blyn::app()->getUIManager()->getSenderControl();
              $activeOperation = Blyn::app()->getActiveOperation();

              if ($sender instanceof BUINode) {
              //reset event Id when switch for operation,app and space
              Blyn::app()->getActiveOperation()->addContextVariable('eventId', NULL);
              }
             * 
             */

            //first try to find eventId from link variable
            $eventId = NULL;
            $activeLink = Blyn::app()->getUIManager()->getActiveLink();
            if ($activeLink != NULL) {
                $eventId = $activeLink->getLinkVariable('eventId');
                //update context variable
                if (is_numeric($eventId) && $eventId > 0) {
                    Blyn::app()->getActiveOperation()->addContextVariable('eventId', $eventId);
                }
            }

            //then try to find eventId from screen context variable
            //if ($eventId == NULL) {
            //$eventId = Blyn::app()->getUIManager()->getCurrentScreen()->getContextVariable('eventId');
            //}
            //then try to find eventId from operation context variable
            if ($eventId == NULL && Blyn::app()->getActiveOperation() != NULL) {
                $eventId = Blyn::app()->getActiveOperation()->getContextVariable('eventId');
            }

            if ($eventId != NULL && $eventId > 0) {
                $eventTable = new BAEventSheet();
                $event = $eventTable->getListById($eventId);
            }
        }

        if ($event != NULL) {
            //special for wePage type, add template for wePage type
            $eventType = $this->getEventTypeByEvent($event);

            /*
              $category = new BACategory();
              $categoryRoot = $category->getRootNode();
              $eventTypeRoot = $categoryRoot->getChild('eventType');
              $eFullName = $eventType->getFullName();
              $erFullName = $eventTypeRoot->getFullName();
              $noRootFullName = str_replace($erFullName . '.', '', $eFullName);
             * 
             */

            //$eventName = $event->getItem('name')->getValue();
            if ($eventType != NULL) {
                $viewPath = $this->populateEventTypeFolderAlias($eventType);
                $templateItem = $event->getItem('template');
                if ($templateItem instanceof BTreeItem) {
                    $template = $templateItem->getValue();
                    $viewPath = $viewPath . '.' . $template;
                }
                return $viewPath;
            }
        }
        return FALSE;
    }

    /**
     * this function use to find event by Id or by eventName+eventType
     * if not specify eventType, will treat eventName as eventType to find
     * @param type $eventContext
     * @param type $eventType
     * @param type $data
     * @return boolean
     */
    public function getEvent($eventContext, $eventType = NULL, $data = NULL) {
        $eventId = NULL;
        $event = NULL;
        $eventName = NULL;

        $eventTable = new BAEventSheet();

        if (is_numeric($eventContext) && $eventContext > 0) {
            $eventId = $eventContext;
            $event = $eventTable->getListById($eventId);
            return $event;
        }

        if ($eventContext instanceof BTreeList) {
            return $eventContext;
        }

        $itemContext = array();
        if (is_string($eventContext)) {
            $eventName = $eventContext;
            if ($eventName != NULL)
                $itemContext['name'] = $eventName;
        }

        if ($eventType == NULL) {
            $eventType = $eventName;
        }

        if ($eventType != NULL) {
            if (is_string($eventType)) {
                $oEventType = $this->getEventTypeByName($eventType);
            }
            if ($eventType instanceof BACategory) {
                $oEventType = $eventType;
            }
            if (isset($oEventType) && $oEventType != NULL) {
                $itemContext['eventTypeId'] = $oEventType->getId();
            }

            $event = $eventTable->getList(array('itemData' => $itemContext));
            return $event;
        }

        return FALSE;
    }

    public function getEventType($typeData, $autoAddType = TRUE) {
        if ($typeData instanceof BACategory) {
            return $typeData;
        }
        if (is_numeric($typeData) && $typeData > 0) {
            return new BACategory($typeData);
        }
        if (is_string($typeData) && $typeData != NULL) {
            $typeRoot = $this->getEventTypeRoot();
            $type = $typeRoot->getChild($typeData);
            if ($type == NULL && $autoAddType) {
                $type = $typeRoot->addChild($typeData);
            }
            return $type;
        }

        if (is_array($typeData)) {
            $typeName = key($typeData);
            $typeAlias = reset($typeData);
            if ($typeAlias == NULL) {
                $typeAlias = $typeName;
            }
            if (is_numeric($typeName)) {
                $typeName = $typeAlias;
            }
            $typeRoot = $this->getEventTypeRoot();
            $type = $typeRoot->getChild($typeName);
            if ($type == NULL && $autoAddType) {
                $type = $typeRoot->addChild(array('name' => $typeName, 'value' => $typeAlias));
            }
            return $type;
        }

        return FALSE;
    }

    public function getEventTypeRoot() {
        $category = new BACategory();
        $rootNode = $category->getRootNode();
        $typeRoot = $rootNode->getChild('eventType');
        if ($typeRoot == NULL) {
            $typeRoot = $rootNode->addChild('eventType');
        }
        return $typeRoot;
    }

    public function getCurrentEvent($data = NULL) {

        $eventId = $this->activeLink->getLinkVariable('eventId');

        if (is_numeric($eventId) && $eventId > 0) {
            Blyn::app()->getActiveOperation()->addContextVariable('eventId', $eventId);
        } else {
            $eventId = Blyn::app()->getActiveOperation()->getContextVariable('eventId');
        }
        if (is_numeric($eventId) && $eventId > 0) {
            $eventTable = new BAEventSheet();
            return $eventTable->getListById($eventId);
        }
        return NULL;
    }

    public function getCurrentEventHome($data = NULL) {

        $eventHome = $this->activeLink->getLinkVariable('eventHome');

        if ($eventHome == NULL) {
            $eventHome = Blyn::app()->getActiveOperation()->getContextVariable('eventHome');
        } else {
            Blyn::app()->getActiveOperation()->addContextVariable('eventHome', $eventHome);
        }

        return $eventHome;
    }

    /**
     * get event list under current space+app
     * @param type $data
     */
    public function getEventView($itemContext = NULL, $eventType = NULL) {
        $app = Blyn::app()->getActiveApp();
        if (method_exists($app, 'getAppPreloadEventListData')) {
            $this->preloadEvent(Blyn::app()->getActiveApp()->getAppPreloadEventListData());
        }

        $eventTable = new BAEventSheet();

        $eventList = array();

        //find by item context
        if ($itemContext != NULL) {
            $eventList = $eventTable->getView(array('itemData' => $itemContext));
        } else {//all event
            $eventList = $eventTable->getView();
        }

        //find by event type
        if ($eventType != NULL) {
            if (is_string($eventType) && $eventType != NULL)
                $eventType = $this->getEventTypeByName($eventType);

            if ($eventType instanceof BACategory) {
                $eventList = $type->getMembers(new BTreeList());
            }
        }

        return $eventList;
    }

    public function getEventRoleList() {
        $roleCooker = new BARoleCooker();
        $event = $this->getCurrentEvent();
        $eventId = $event->getId();
        $eventRoleList = $roleCooker->getRoleEventList(NULL, $eventId);
        return $eventRoleList;
    }

    public function getEventHomeList($event = NULL) {

        if (get_class($this) == 'BAEventCooker') {
            if ($event == NULL || $event == FALSE) {
                $event = $this->getCurrentEvent();
            } else {
                $event = $this->getEvent($event);
            }
            if ($event != NULL) {
                $eventType = $this->getEventTypeByEvent($event);
                $eventTypeName = $eventType->getName();
            }
            $cookerClass = 'BA' . ucfirst($eventTypeName) . 'Cooker';
            $cooker = new $cookerClass();
            if (method_exists($cooker, 'getEventHomeList')) {
                return $cooker->getEventHomeList();
            }
        } 
        
        return array(
            'user' => 'user',
            'admin' => 'admin',
            'member' => 'member',
            'customer' => 'customer'
        );
    }

    /**
     * 
     * @param type $roleData
     * @param type $eventData
     */
    public function getEventHomeByRole($roleData = NULL, $eventData = NULL) {

        $roleId = NULL;
        $roleCooker = new BARoleCooker();

        $role = $roleCooker->getRole($roleData);

        if ($role != NULL) {
            $eventRoleList = $roleCooker->getRoleEventList($role, $eventData);

            if ($eventRoleList != NULL) {
                $eventRole = reset($eventRoleList);
                $eventRoleData = $eventRole->getItemsInArray();

                if (isset($eventRoleData['eventHome'])) {
                    return $eventRoleData['eventHome'];
                }
            }

            //如果当前角色中没有找到EVENTHOME,就会到PARENT ROLE里面找，直到
            //找到为止，如果没有PARENT了，就返回FALSE
            if ($role instanceof BRole) {
                while (TRUE) {
                    $parentRole = $role->getParent();
                    if ($parentRole == NULL) {
                        return FALSE;
                    }
                    $eventRoleList = $roleCooker->getRoleEventList($parentRole, $eventData);

                    if ($eventRoleList != NULL) {
                        $eventRole = reset($eventRoleList);
                        $eventRoleData = $eventRole->getItemsInArray();

                        if (isset($eventRoleData['eventHome'])) {
                            return $eventRoleData['eventHome'];
                        }
                    }
                    $role = $parentRole;
                }
            }
        }
    }

    public function getEventHomeListData() {
        return $this->getEventHomeList();
    }

    /*
      public function getAllEventHomeByUser($eventData = NULL, $roleData = NULL, $user = NULL) {

      $roleCooker = new BARoleCooker();

      $userRoles = $roleCooker->getAllUserRoles(NULL, $user);

      $eventRoleHomeList = array();

      $eventList = array();

      if ($eventData != NULL) {
      $event = $this->getEvent($eventData);
      $eventList[$event->getId()] = $event;
      } else {
      $eventList = $this->getEventView();
      }

      foreach ($eventList as $eventId => $event) {
      foreach ($userRoles as $roleId => $role) {
      $home = $this->getEventHomeByRole($roleId, $event);
      $item = array();
      $item['eventId'] = $eventId;
      $item['roleId'] = $roleId;
      $item['eventHome'] = $home;
      array_push($eventRoleHomeList, $item);
      }
      }

      return $eventRoleHomeList;
      }
     * 
     */

    /**
     * this function will check whether user is allowed to 
     * add event in app
     */
    public function isUserAllowedAddEvent() {
        $roleCooker = new BARoleCooker();
        $spaceAdminRole = $roleCooker->getRole(BRole::Role_Space_Admin);
        $sAdminRoleId = $spaceAdminRole->getId();

        $user = Blyn::app()->getCurrentUser();
        $userRoles = $roleCooker->getAllUserRoles();
        $roleIdList = array_keys($userRoles);
        //只要系统管理员可以添加功能
        if (in_array($sAdminRoleId, $roleIdList)) {
            return TRUE;
        }

        return FALSE;
    }

    public function onShowEventList($control = NULL, $eventType = NULL, $data = NULL) {
        //$this->showEventListByOperation($control);

        if (!$control instanceof BUIControl) {
            $control = $this->updateControl;
        }

        $operation = Blyn::app()->getActiveOperation();
        $operationName = $operation->getName();

        $roleCooker = new BARoleCooker();
        $userEventList = $roleCooker->getUserEventList();

        /*
          if ($operationName == 'admin') {
          $userEventList = $roleCooker->getUserEventList(BRole::Role_Space_Admin);
          }
          if ($operationName == 'customer') {
          $userEventList = $roleCooker->getUserEventList(BRole::Role_Space_customer);
          }
          if ($operationName == 'member') {
          $userEventList = $roleCooker->getUserEventList(BRole::Role_Space_Member);
          }
          if ($operationName == 'eventPanel') {
          $userEventList = $roleCooker->getUserEventList();
          }
         * 
         */

        /**
         * below code remove event not below to specifi eventType
         */
        if ($eventType != NULL) {
            $oEventType = $this->getEventType($eventType);
            $allEventType = $oEventType->getChildren(NULL, TRUE);
            $idList = array_keys($allEventType);
            array_push($idList, $oEventType->getId());
            foreach ($userEventList as $key => $list) {
                if ($list->getItem('eventTypeId') != NULL) {
                    $eventTypeId = $list->getItem('eventTypeId')->getValue();
                    if (!in_array($eventTypeId, $idList)) {
                        unset($userEventList[$key]);
                    }
                }
            }
        }

        $control->addRenderView('eventList', 'event_list', array('userEventList' => $userEventList));
    }

    public function onShowAddEvent($data = NULL) {

        $eventId = $this->activeLink->getLinkVariable('eventId');

        $this->updateControl->addRenderView('eventAdd', 'event_add', array(
            'eventId' => $eventId));
    }

    public function onShowEventHome($data = NULL) {
        /*
          $activeLink = Blyn::app()->getUIManager()->getActiveLink();
          //$eventId = $activeLink->getLinkVariable('eventId');
          //$eventId = $this->getCurrentEvent()->getId();
          $operationName = Blyn::app()->getActiveOperation()->getName();
          $eventTable = new BAEventSheet();
          $event = $this->getCurrentEvent();
          $eventId = $event->getId();
          $eventName = $event->getItem('name')->getValue();
         * 
         */

        //special for wePage type, add template for wePage type
        /*
          $eventType = $this->getEventTypeByEvent($event);
          $wePageEventType = $this->getEventTypeByName('wePage');
          if ($eventType->isChildOf($wePageEventType)) {
          $typeName = $eventType->getName();
          $this->updateControl->setViewPath($this->populateEventTypeFolderAlias($eventType));
          }
         * 
         */

        //$viewName = $event->getItem($operationName . 'Home')->getValue();
        //$viewName = $eventName . '_' . $operationName;

        //$eventHome = $this->activeLink->getLinkVariable('eventHome');
        $eventHome = $this->getCurrentEventHome();

        $updateControl = $this->updateControl;

        $eventType = $this->getCurrentEventType();
        $eventTypeName = $eventType->getName();
        $updateControl->setViewTemplate('cooker.' . $eventTypeName);

        //$updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $updateControl->addRenderView('eventHome', $eventHome);
    }

    //this function use to add event usually created in admin view
    //after add, return to list
    public function onSaveEvent($data = NULL) {
        $eventId = $this->activeLink->getLinkVariable('eventId');

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'add_event');

        $itemData = array();
        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            if ($value != NULL || $value != '') {
                $itemData[$name] = $value;
            }
        }
        $eventName = $itemData['name'];
        unset($itemData['name']);
        $eventTypeData = $itemData['eventType'];
        unset($itemData['eventType']);

        $eventType = $this->getEventType($eventTypeData);

        $eventTable = new BAEventSheet();
        if ($eventId != NULL && $eventId != 0) {
            $event = $eventTable->getListById($eventId);
            //save exist list
            $event->addItems($itemData);
        } else {
            $event = $this->addEvent($eventName, $eventType, $itemData);
            //新建功能的时候，需要允许机构管理员对功能进行设置

            $roleCooker = new BARoleCooker();
            $spaceAdminRole = $roleCooker->getRole(BRole::Role_Space_Admin);
            $roleCooker->addRoleEvent($spaceAdminRole->getId(), $event->getId(), array(
                //'eventHome' => 'admin',
                //'eventTitle' => '设置功能',
                'allowModify' => 'yes',
                'allowDelete' => 'yes'
            ));
            /*
              $eventTable = new BAEventSheet(NULL, 'eventTypeCount');
              $list = $eventTable->getList(array('itemData' => array('eventTypeId' => $eventType->getId())));
              if ($list != NULL) {
              $count = $list->getItem('count')->getValue();
              $count +=1;
              $list->addItem('count', $count);
              } else {
              $eventTable->addList(array('eventTypeId' => $eventType->getId(), 'count' => 1));
              }
             * 
             */
        }

        $this->onShowEventList();
    }

    public function onDeleteEvent($data = NULL) {
        $eventId = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('eventId');
        if ($eventId != NULL) {
            $eventTable = new BAEventSheet();
            $event = $eventTable->getListById($eventId);
            $eventTable->deleteList($eventId);
            //$event->getListNode()->status = -1;
            //$event->save();
        }
        $this->onShowEventList();
    }

    public function onHelpEvent($data = NULL) {
        $currentApp = Blyn::app()->getActiveApp();

        $currentAppName = $currentApp->getName();
        header('Location: ' . Yii::app()->request->baseUrl . '/dokuwiki/doku.php?id=' . $currentAppName);
//        header('Location: ' . Yii::app()->request->baseUrl . '/dokuwiki/doku.php?id=start');
//       $wikiPage = Yii::app()->request->baseUrl.'/dokuwiki/doku.php?id=wiki:welcome';
//       echo "<script language=\"text/javascript\">window.open($wikiPage);</script>";
    }

    /**
     * 
     * @param type $eventType
     * @param type $itemContex
     * @param type $data
     */
    public function showEventListByOperation($control = NULL, $eventType = NULL, $itemContex = null, $data = NULL) {

        //add embedded event for appAdmin
        $eventShareEvent = $this->getEvent('eventShare', 'changeless.appAdmin');
        if ($eventShareEvent == FALSE) {
            $this->addEventType('changeless.appAdmin', '系统功能');
            $this->addEvent('eventShare', 'changeless.appAdmin', array('alias' => '机构功能分享'));
        }

        if ($control == NULL) {
            //$updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            $updateControl = $this->updateControl;
        } else {
            $updateControl = $control;
        }

        $eventTable = new BAEventSheet();

        $eventList = array();

        //find by item context
        if ($itemContex != NULL) {
            $eventList = $eventTable->getView(array('itemData' => $itemContex));
        } else {//all event
            $eventList = $eventTable->getView();
        }

        //add event list from related space
        $appAdminControl = new BUIAppAdmin();
        $eventList+= $appAdminControl->getSharedEventList();

        //find by event type
        if ($eventType != NULL) {
            if (is_string($eventType) && $eventType != NULL)
                $eventType = $this->getEventTypeByName($eventType);

            if ($eventType instanceof BACategory) {
                $eventList = $type->getMembers(new BTreeList());
            }
        }

        //retreive event list for current operation
        $finalEventList = array();
        foreach ($eventList as $id => $event) {
            $activeOperation = Blyn::app()->getActiveOperation();
            if ($activeOperation->getName() == 'admin') {//admin show all event
                $finalEventList[$id] = $event;
            } else {
                //$eventHomeField = $event->getItem('name')->getValue() . ucfirst($activeOperation->getName());
                $opHomeField = $activeOperation->getName() . 'Home';
                $eventOperationHome = $event->getItem($opHomeField)->getValue();
                if ($eventOperationHome != NULL || $eventOperationHome != '') {
                    $finalEventList[$id] = $event;
                }
            }
        }

        //$eventDescription = $list->getItem('description')->getValue();
        $updateControl->addRenderView('eventList', 'event_list', array('eventList' => $finalEventList));
    }

    public function onShowEventRoleList($control = NULL) {

        if (!$control instanceof BUIControl) {
            $control = $this->updateControl;
        } else {
            //$this->updateControl->addControl($control);
        }

        $eventRoleList = $this->getEventRoleList();

        $control->addRenderView('eventRoleList', 'event_role_list', array('eventRoleList' => $eventRoleList));
    }

    public function onShowAddEventRole() {

        $model = BAModelCooker::getDynamicModel();
        $model->addField('isChecked');
        $model->addField('eventHome');
        $model->addField('mobileTheme');

        $viewData = array();
        $viewData['model'] = $model;

        $spaceRoleList = BARoleCooker::getAllSpaceRoleData(NULL, 'allroles');
        $event = $this->getCurrentEvent();
        $eventId = $event->getId();

        $roleCooker = new BARoleCooker();
        $eventRoleList = $roleCooker->getRoleEventList(NULL, $eventId);

        foreach ($eventRoleList as $list) {
            $roleId = $list->getItem('roleId')->getValue();
            unset($spaceRoleList[$roleId]);
        }

        $viewData['roleListData'] = $spaceRoleList;

        $this->updateControl->addRenderView('addEventRole', 'event_role_add', $viewData);
    }

    public function onShowModifyEventRole() {

        $eventRoleId = $this->activeLink->getLinkVariable('eventRoleId');
        $roleCooker = new BARoleCooker();
        $eventRole = $roleCooker->getRoleEventById($eventRoleId);
        $eventRoleData = $eventRole->getItemsInArray();

        $eventId = $eventRoleData['eventId'];
        $roleId = $eventRoleData['roleId'];
        $home = isset($eventRoleData['eventHome']) ? $eventRoleData['eventHome'] : NULL;
        $mobileTheme = isset($eventRoleData['mobileTheme']) ? $eventRoleData['mobileTheme'] : NULL;

        $this->updateControl->addRenderView(
                'modifyEventRole', 'modifyEventRole', array('eventRoleData' => $eventRoleData));
    }

    public function onModifyEventRole() {
        $postData = $this->postData;
        $eventRoleId = $this->activeLink->getLinkVariable('eventRoleId');

        $roleCooker = new BARoleCooker();
        $eventRole = $roleCooker->getRoleEvent($eventRoleId);

        $eventRole->addItems($postData);

        $this->onShowEventRoleList();
    }

    public function onAddEventRole() {

        $event = $this->getCurrentEvent();
        $eventId = $event->getId();

        $roleCooker = new BARoleCooker();

        if (isset($_POST['BDynamicFormModel'])) {
            $checkedItems = $_POST['BDynamicFormModel'];

            foreach ($checkedItems as $id => $value) {
                if (is_array($value)) {
                    if (isset($value['isChecked'])) {
                        $isChecked = $value['isChecked'];

                        if ($isChecked) {
                            $eventHome = $value['eventHome'];
                            $roleId = $id;
                            $data = array('eventHome' => $eventHome);
                            $mobileTheme = isset($value['mobileTheme']) ? $value['mobileTheme'] : NULL;
                            if ($mobileTheme != NULL) {
                                $data['mobileTheme'] = $mobileTheme;
                            }
                            $list = $roleCooker->addRoleEvent($roleId, $eventId, $data);
                        }
                    }
                }
            }
        }

        $this->onShowEventRoleList();
    }

    public function onDeleteEventRole() {
        $eventRoleId = $this->activeLink->getLinkVariable('eventRoleId');

        $roleCooker = new BARoleCooker();
        $eventRoleTable = $roleCooker->getRoleEventTable();

        if (is_numeric($eventRoleId) && $eventRoleId > 0) {
            $eventRoleTable->deleteList($eventRoleId);
        }

        $this->onShowEventRoleList();
    }

}
